from flask import request,jsonify
from db import db,Users,app


@app.route('/users')
def get_users():
    users = Users.query.all()  # 查询所有用户
    print(users)
    return {
        'users': [{
            'id': u.id,
            'username': u.username,
            'email':u.email
        } for u in users]
    }


@app.route('/add_user', methods=['POST'])
def add_user():
    data = request.json # json中拿
    new_user = Users(username=data['username'], email=data['email'])
    db.session.add(new_user)# 新增用户
    db.session.commit()  # 提交事务
    return {'message': 'User created'}, 201

@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    user = Users.query.get_or_404(user_id)
    try:
        db.session.delete(user) # 根据id删除用户
        db.session.commit()
        return jsonify({"message": "Deleted successfully"})
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True)